package com.wbp.cms.web.controller.admin;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;
import com.wbp.cms.client.customer.domain.CustomerDO;
import com.wbp.cms.client.customer.query.CustomerQuery;
import com.wbp.cms.client.customer.service.CustomerService;
import com.wbp.cms.client.result.BaseResultCode;
import com.wbp.cms.client.result.Result;
import com.wbp.cms.client.user.domain.UserDO;
import com.wbp.cms.client.util.IdCardUtil;
import com.wbp.cms.client.util.JsonUtils;
import com.wbp.cms.client.util.MD5Utils;
import com.wbp.cms.web.controller.BaseController;
import com.wbp.cms.web.util.SessionUtil;


/**
 * 后台客户管理
 * @Description: 
 * @Department:
 * @author andy.lhc
 * @date 2016年3月10日 下午3:38:10 
 */
@Controller("customerMgrController")
@RequestMapping("/custmgr")
public class CustomerMgrController  extends BaseController {

  private static final Logger  logger = Logger.getLogger(CustomerMgrController.class) ;
  
  @Resource(name="customerService")
  private CustomerService  customerService ;
  
  
  @RequestMapping("/tolist")
  public ModelAndView  toList(){
    ModelAndView mv = new ModelAndView();
    mv.setViewName("admin/customer/customerList"); 
    return mv ;
  }
  
  
  /*@RequestMapping("/list")
  public ModelAndView doList( HttpServletRequest request, @RequestParam(value = "pageNo",
      required = false, defaultValue = "1") int pageNo,@RequestParam(value = "pageSize",
      required = false, defaultValue = "50") int pageSize) {

    ModelAndView mv = new ModelAndView();
    mv.setViewName("admin/customer/customerList"); 
    
    CustomerQuery  customerQuery =new CustomerQuery();
    customerQuery.setPageNo(pageNo);
    customerQuery.setPageSize(pageSize);
    
    UserDO  user  = SessionUtil.getCurrentUser(request.getSession()) ;
    customerQuery.setUserId(user.getId());
    customerQuery.setRecommendUserOrganizationId(user.getOrganizationId());
    
    Result<List<CustomerDO>> result = customerService.queryUsers(customerQuery) ;
    if(result.isSuccess() && result.getData()!=null &&  result.getData().size() > 0){
        mv.addObject("count", result.getTotal()) ;
        mv.addObject("customerList", result.getData()) ;
    }
    return mv;
  }*/
  
  /**
   * 跳到新增客户页面
   * @param customerDO
   * @return
   */
  @RequestMapping("/toadd")
  public ModelAndView  toAddCustomer(){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/customer/customerAdd"); 
     
     return  mv ;
  }
  
  /**
   * 新增一条客户记录
   * @param customerDO
   * @return
   */
  @RequestMapping(value="/doadd" ,method = RequestMethod.POST  ,produces = "application/json;charset=UTF-8"  )
  @ResponseBody
  public String  doAddCustomer(HttpServletRequest request  /*, @RequestBody CustomerDO  customerDO */ ){
    try{
      
       String params = this.getParameters(request).get("params") ; //   request.getParameter("params") ;
       if(params == null  || params.equals(""))
           return JsonUtils.toJson(Result.buildError("参数不合法")) ;
       CustomerDO customerDO = JsonUtils.toObject(params, CustomerDO.class) ;
        
        if(StringUtils.isEmpty(customerDO.getUserName()))
          return JsonUtils.toJson(Result.buildError("客户名不能为空")) ;
        if(StringUtils.isEmpty(customerDO.getPwd()))
          return JsonUtils.toJson(Result.buildError("客户密码不能为空")) ;
        customerDO.setPwd( MD5Utils.strToMD5(customerDO.getPwd() + customerDO.getUserName()) ) ; 
        
        UserDO  user = SessionUtil.getCurrentUser(request.getSession()) ;
        if(user == null){
            return JsonUtils.toJson(Result.buildError("请重新登录")) ;
        }
        if(customerDO.getIdCard() !=null && !customerDO.getIdCard().equals("")){
           if(!IdCardUtil.verify(customerDO.getIdCard()))
             return JsonUtils.toJson(Result.buildError("身份证号码不合法")) ;
        }
        customerDO.setUserId(user.getId()); 
        customerDO.setRecommendUserName(user.getUserName());
        
        if( this.customerService.queryCustomerByUserName(customerDO.getUserName()) !=null )
           return JsonUtils.toJson(Result.buildError("已经存在此用户名称")) ; 
        
        Long  customerId =this.customerService.addCustomer(customerDO) ;
        
        return  JsonUtils.toJson(Result.buildSuccess(customerId)) ;
    }catch(Throwable e){
      logger.error(BaseResultCode.CUSTOMER_ADD_CUSTOMER_ERROR.getErrMsg(), e);
      return JsonUtils.toJson(Result.buildError(BaseResultCode.CUSTOMER_ADD_CUSTOMER_ERROR));
    }
  }
  
  /**
   * 跳到 修改 客户页面
   * @param customerDO
   * @return
   */
  @RequestMapping("/toedit")
  public ModelAndView  toEditCustomer(@RequestParam(value="customerId",required=true,defaultValue="0") Long customerId,
      @RequestParam(value="type",required=true,defaultValue="0") Integer type){
     ModelAndView mv = new ModelAndView();
     mv.setViewName("admin/customer/customerEdit"); 
     
     mv.addObject("customer",  this.customerService.queryCustomerById(customerId) ) ;
     
     mv.addObject("type", type) ;
     return  mv ;
  }
  
  /**
   * 编辑客户信息
   * @param customerDO
   * @return
   */
  @RequestMapping(value="/doedit", produces = "application/json;charset=UTF-8",method = {RequestMethod.GET, RequestMethod.POST})
  @ResponseBody
  public String  doEditCustomer(HttpServletRequest request /*@ModelAttribute CustomerDO  customerDO*/ ){
    try{
      
        String params = this.getParameters(request).get("params") ; //   request.getParameter("params") ;
        if(params == null  || params.equals(""))
            return JsonUtils.toJson(Result.buildError("参数不合法")) ;
        CustomerDO customerDO = JsonUtils.toObject(params, CustomerDO.class) ;
      
        if(customerDO == null )
          return JsonUtils.toJson(Result.buildError("参数不合法")) ;
        if(customerDO.getId() == null || customerDO.getId() <=0)
          return JsonUtils.toJson(Result.buildError("请重新刷新页面再修改客户信息")) ;
        if(customerDO.getIdCard() !=null && !customerDO.getIdCard().equals("")){
          if(!IdCardUtil.verify(customerDO.getIdCard()))
            return JsonUtils.toJson(Result.buildError("身份证号码不合法")) ;
       }
        
        boolean  result =this.customerService.modifyCustomer(customerDO) ;
        
        return  JsonUtils.toJson(Result.buildSuccess(result),true) ;
    }catch(Throwable e){
      logger.error(BaseResultCode.CUSTOMER_MODIFY_CUSTOMER_ERROR.getErrMsg(), e);
      return JsonUtils.toJson(Result.buildError(BaseResultCode.CUSTOMER_MODIFY_CUSTOMER_ERROR));
    }
  }
  
  /**
   * 查询方法
   * @param userName
   * @param mobileNumber
   * @param realName
   * @param gender
   * @param customerLevel
   * @param pageNo
   * @param pageSize
   * @return
   */
  @RequestMapping(value="/query", produces = "application/json;charset=UTF-8",method = {RequestMethod.GET, RequestMethod.POST})
  @ResponseBody
  public String doQuery(HttpServletRequest request , @RequestParam(value = "userName",
      required = false, defaultValue = "") String userName, @RequestParam(value = "mobileNumber",
      required = false, defaultValue = "") String mobileNumber,@RequestParam(value = "realName",
      required = false, defaultValue = "") String realName,@RequestParam(value = "gender",
      required = false, defaultValue = "0") int gender ,@RequestParam(value = "customerLevel",
      required = false, defaultValue = "0") int customerLevel ,@RequestParam(value = "start",
      required = false, defaultValue = "1") int start,@RequestParam(value = "length",
      required = false, defaultValue = "10") int pageSize) {

   
    Map<String,String> maps = this.getParameters(request) ;
 
    CustomerQuery  customerQuery =new CustomerQuery();
   // customerQuery.setPageNo(pageNo);
    customerQuery.setStart(start);
    customerQuery.setPageSize(pageSize);
    if(StringUtils.isNotEmpty(userName))
        customerQuery.setUserName(userName);
     
    if(StringUtils.isNotEmpty(mobileNumber))
        customerQuery.setMobileNumber(mobileNumber); 
    if(StringUtils.isNotEmpty(realName))
        customerQuery.setRealName(realName);
    if(gender >0)
        customerQuery.setGender(gender);
    if(customerLevel >0)
        customerQuery.setCustomerLevel(customerLevel);
    
    UserDO  user = SessionUtil.getCurrentUser(request.getSession()) ;
    if(!this.isSuperUser(user.getUserName())){
        customerQuery.setRecommendUserOrganizationId(user.getOrganizationId());
        //customerQuery.setUserId(user.getId());
    }
    Result<List<CustomerDO>> result = customerService.queryUsers(customerQuery) ;
    if(result.isSuccess() && result.getData() !=null && !result.getData().isEmpty() ){
       for(CustomerDO c : result.getData()){
         String tmpMobileNumber = c.getMobileNumber() ;
         String tmpIdCard = c.getIdCard() ;
         c.setMobileNumber(getMobileNumber(tmpMobileNumber)); 
         c.setIdCard(getIdCard(tmpIdCard)); 
          
       }
    }
    
    return new Gson().toJson(getDataTableMapData(result,maps.get(DT_KEY_DRAW) )) ;
     
  }
 
}
